package com.qyxx.platform.gsmng.common.service;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.HistoryService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.pvm.delegate.ActivityExecution;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.qyxx.platform.common.orm.hibernate.HibernateDao;
import com.qyxx.platform.gsc.cache.SqlCache;
import com.qyxx.platform.gsc.utils.Constants;
import com.qyxx.platform.gsmng.common.dao.GsMngDao;
import com.qyxx.platform.sysmng.exception.GsException;

/**
 *流向处理类
 */
@Service
@Transactional
public class FlowCondition extends HibernateDao<Object, Long> {

	private GsMngDao gsMngDao;
	
	private HistoryService historyService;
	
	@Autowired
	public void setGsMngDao(GsMngDao gsMngDao) {
		this.gsMngDao = gsMngDao;
	}	
	
	@Autowired
	public void setHistoryService(HistoryService historyService) {
		this.historyService = historyService;
	}

	public FlowCondition() {
		super();
		// TODO Auto-generated constructor stub
	}	
	
	public Boolean isMoreThanNumeric(ActivityExecution execution,String propertyName,Long num){
		String businessKey = execution.getProcessBusinessKey();
		String a[] = businessKey.split("\\|");
		String bname = a[0];
		Long bid = Long.valueOf(a[1]);
		Map<String, Object> loadMap = gsMngDao.get(bid,bname);
		Number number = (Number)loadMap.get(propertyName);
		Long val = number.longValue();
		if(val==null || val<num){
			return false;	
		} else if (val>num){
			return true;
		}
		return false;	
	}
	
	public Boolean isNumeric(ActivityExecution execution,String propertyName,Long num){
		String businessKey = execution.getProcessBusinessKey();
		String a[] = businessKey.split("\\|");
		String bname = a[0];
		Long bid = Long.valueOf(a[1]);
		Map<String, Object> loadMap = gsMngDao.get(bid,bname);
		Number number = (Number)loadMap.get(propertyName);
		Long val = number.longValue();
		if(val!=null && val.equals(num)){
			return true;
		}else{
			return false;	
		}	
	}
	
	public Boolean isType(ActivityExecution execution,String propertyName,String name){
		String businessKey = execution.getProcessBusinessKey();
		String a[] = businessKey.split("\\|");
		String bname = a[0];
		Long bid = Long.valueOf(a[1]);
		Map<String, Object> loadMap = gsMngDao.get(bid,bname);
		String val = (String)loadMap.get(propertyName);
		if(val.equals(name)){
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 根据sql语句查询的结果和传入参数比较
	 * 
	 * @param execution
	 * @param ruleName
	 * @param value
	 * @return
	 */
	public Boolean isSql(ActivityExecution execution,String ruleName,String value){
		String businessKey = execution.getProcessBusinessKey();
		String a[] = businessKey.split("\\|");
		Long bid = Long.valueOf(a[1]);
		final Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("id",bid );
		String sqlKey = Constants.RULE_SUFFIX + Constants.NAME_SPLIT_SYMBOL + ruleName;
		final String namedSql = SqlCache.getInstance().getSqlContent(sqlKey);
		if(StringUtils.isBlank(namedSql)) {
			throw new GsException(sqlKey + "对应的sql找不到");
		}
		SQLQuery cq = getSession().createSQLQuery(namedSql);
		if(null!=paramMap) {
			cq.setProperties(paramMap);
		}
		Object val = cq.uniqueResult();
		if(null!=val) {
			if(value.equals(val.toString())) {
				return true;
			} else {
				return false;
			}
		} else {
			return (val == value);
		}
	}
	
	/**
	 * 根据业务规则获取整数值
	 * 
	 * @param execution
	 * @param ruleName 业务规则-sql语句
	 * @param defaultValue 默认值
	 * @return
	 */
	public Long getLongValueByParam(ActivityExecution execution,String ruleName,Long defaultValue){
		String val = getStringValueByParam(execution, ruleName, "");
		return NumberUtils.toLong(val, defaultValue);
	}
	
	/**
	 * 根据业务规则获取小数值
	 * 
	 * @param execution
	 * @param ruleName 业务规则-sql语句
	 * @param defaultValue 默认值
	 * @return
	 */
	public Double getDoubleValueByParam(ActivityExecution execution,String ruleName,Double defaultValue){
		String val = getStringValueByParam(execution, ruleName, "");
		return NumberUtils.toDouble(val, defaultValue);
	}
	
	/**
	 * 根据业务规则获取字符串值
	 * 
	 * @param execution
	 * @param ruleName 业务规则-sql语句
	 * @param defaultValue 默认值
	 * @return
	 */
	public String getStringValueByParam(ActivityExecution execution,String ruleName, String defaultValue){
		String businessKey = execution.getProcessBusinessKey();
		String a[] = businessKey.split("\\|");
		Long bid = Long.valueOf(a[1]);
		final Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("id",bid);
		paramMap.put("handleUserId", execution.getVariable("handleUserId"));
		//paramMap.put("userId");
		String sqlKey = Constants.RULE_SUFFIX + Constants.NAME_SPLIT_SYMBOL + ruleName;
		final String namedSql = SqlCache.getInstance().getSqlContent(sqlKey);
		if(StringUtils.isBlank(namedSql)) {
			throw new GsException(sqlKey + "对应的sql找不到");
		}
		SQLQuery cq = getSession().createSQLQuery(namedSql);
		cq.setProperties(paramMap);
		List<Object> list = cq.list();
		String val = null;
		if(!list.isEmpty()) {
			val = String.valueOf(list.get(0));
		}
		return StringUtils.defaultString(val, defaultValue);
	}
	
	/**
	 * 根据环节名称获取历史处理者
	 * 
	 * @param execution
	 * @param taskName
	 * @return
	 */
	public String getHandleUserByTaskName(ActivityExecution execution, String taskName) {
		String processInstanceId = execution.getProcessInstanceId();
		List<HistoricTaskInstance> htie =(List<HistoricTaskInstance>) historyService.createHistoricTaskInstanceQuery()
								.processInstanceId(processInstanceId).taskName(taskName).orderByTaskId().desc().list();
		return htie.get(0).getAssignee();
	}
}
